package com.gm.wholesale.bluetooth.service;
import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import androidx.core.app.ActivityCompat;

import com.gm.commonlib.util.logUtils.LogUtil;
import com.gm.commonlib.views.toast.ToastUtil;
import com.gm.wholesale.bluetooth.BluetoothUtil;
import com.gm.wholesale.bluetooth.bean.DeviceBean;
import com.gm.wholesale.util.AppUtil;
import com.youth.banner.util.LogUtils;

import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;
public class BluetoothService {
    // Debugging
    private static final String TAG = "gm_app";
    private static final boolean D = false;
    // Unique UUID for this application
    private static final UUID MY_UUID_SECURE =
            UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

    // Member fields
    private final BluetoothAdapter mAdapter;
    private final Handler mHandler;
    private ConnectThread mConnectThread;
    private ConnectedThread mConnectedThread;
    Context ctx;
    private int mState;

    // Constants that indicate the current connection state
    public static final int STATE_NONE = 0;       // we're doing nothing
    public static final int STATE_LISTEN = 1;     // now listening for incoming connections
    public static final int STATE_CONNECTING = 2; // now initiating an outgoing connection
    public static final int STATE_CONNECTED = 3;  // now connected to a remote device


    /**
     * Constructor. Prepares a new BluetoothChat session.
     * @param context  The UI Activity Context
     * @param handler  A Handler to send messages back to the UI Activity
     */
    public BluetoothService(Context context, Handler handler) {
        mAdapter = BluetoothAdapter.getDefaultAdapter();
        mState = STATE_NONE;
        ctx = context;
        mHandler = handler;
    }


    /**
     * Set the current state of the chat connection
     * @param state  An integer defining the current connection state
     */
    public synchronized void setState(int state) {
        if (D) Log.d(TAG, "setState() " + mState + " -> " + state);
        mState = state;
    }

    /**
     * Return the current connection state. */
    public synchronized int getState() {
        return mState;
    }

    public BluetoothDevice mdevice;

    public synchronized void connect(BluetoothDevice device) {
        if (D) Log.d(TAG, "connect to: " + device);
        mdevice = device;
        if (mConnectThread != null) {
            mConnectThread.cancel();
            mConnectThread = null;
        }
        //  }

        if (mConnectedThread != null) {
            mConnectedThread.cancel();
            mConnectedThread = null;
        }

        // Start the thread to connect with the given device
        mConnectThread = new ConnectThread(device);
        mConnectThread.start();
        setState(STATE_CONNECTING);
    }


    /**
     * Start the ConnectedThread to begin managing a Bluetooth connection
     * @param socket  The BluetoothSocket on which the connection was made
     * @param device  The BluetoothDevice that has been connected
     */
    public synchronized void connected(BluetoothSocket socket, BluetoothDevice
            device, final String socketType) {
        if (D) Log.d(TAG, "connected, Socket Type:" + socketType);

        // Cancel the thread that completed the connection
        if (mConnectThread != null) {
            mConnectThread.cancel();
            mConnectThread = null;
        }

        // Cancel any thread currently running a connection
        if (mConnectedThread != null) {
            mConnectedThread.cancel();
            mConnectedThread = null;
        }

        //Log.d(TAG, "2");
        // Start the thread to manage the connection and perform transmissions
        mConnectedThread = new ConnectedThread(socket, socketType);
        mConnectedThread.start();
        // Send the name of the connected device back to the UI Activity
        setState(STATE_CONNECTED);
    }

    /**
     * Stop all threads
     */
    public synchronized void stop() {
        if (D) Log.d(TAG, "stop");

        if (mConnectThread != null) {
            mConnectThread.cancel();
            mConnectThread = null;
        }

        if (mConnectedThread != null) {
            mConnectedThread.cancel();
            mConnectedThread = null;
        }

        setState(STATE_NONE);
    }

    /**
     * Write to the ConnectedThread in an unsynchronized manner
     * @param out The bytes to write
     * @see ConnectedThread#write(byte[])
     */
    public void write(byte[] out) {
        // Create temporary object
        ConnectedThread r;
        // Synchronize a copy of the ConnectedThread
        synchronized (this) {
            if (mState != STATE_CONNECTED) return;
            r = mConnectedThread;
        }
        // Perform the write unsynchronized
        r.write(out);
    }

    /**
     * Indicate that the connection attempt failed and notify the UI Activity.
     */
    private void connectionFailed() {
        // Send a failure message back to the Activity
        // Start the service over to restart listening mode
        if (D) Log.d(TAG, "connected fail");
        Message message = new Message();
        message.what = 2;
        message.arg1 = 0;
        setState(STATE_NONE);
        mHandler.sendMessage(message);
    }

    /**
     * Indicate that the connection was lost and notify the UI Activity.
     */
    private void connectionLost() {
        // Send a failure message back to the Activity
        if (D) Log.d(TAG, "connected lost");
        // Start the service over to restart listening mode
        Message message = new Message();
        message.what = 2;
        message.arg1 = 1;
        setState(STATE_NONE);
        mHandler.sendMessage(message);
    }

    private void connectionok() {
        // Send a failure message back to the Activity
        if (D) Log.d(TAG, "connected ad");
        // Start the service over to restart listening mode
        Message message = new Message();
        message.what = 2;
        message.arg1 = 2;
        mHandler.sendMessage(message);
    }


    /**
     * This thread runs while attempting to make an outgoing connection
     * with a device. It runs straight through; the connection either
     * succeeds or fails.
     */
    private class ConnectThread extends Thread {
        private final BluetoothSocket mmSocket;
        private final BluetoothDevice mmDevice;
        private String mSocketType;

        public ConnectThread(BluetoothDevice device) {
            mmDevice = device;
            BluetoothSocket tmp = null;

            // Get a BluetoothSocket for a connection with the
            // given BluetoothDevice
            try {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                    if (ActivityCompat.checkSelfPermission(ctx, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
                        ToastUtil.showToast("没有蓝牙权限，请打开");
                    } else {
                        tmp = device.createRfcommSocketToServiceRecord(MY_UUID_SECURE);
                    }
                } else {
                    tmp = device.createRfcommSocketToServiceRecord(MY_UUID_SECURE);
                }


            } catch (Exception e) {
                Log.e(TAG, "Socket Type: " + mSocketType + "create() failed", e);
            }
            mmSocket = tmp;
        }


        public void run() {
            if (D) Log.i(TAG, "BEGIN mConnectThread SocketType:" + mSocketType);
            setName("ConnectThread" + mSocketType);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                if (ActivityCompat.checkSelfPermission(ctx, Manifest.permission.BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED) {
                    ToastUtil.showToast("没有蓝牙权限请打开权限");
                    return;
                }
            }
            if (mAdapter != null) {
                mAdapter.cancelDiscovery();
            }
            try {
                if (mmSocket != null) {
                    mmSocket.connect();
                }
            } catch (Exception e) {
                e.printStackTrace();
                LogUtils.d("连接失败： "+e.toString());
                if (mdevice != null) {
                    AppUtil.removeBondDevice(mmDevice);
                }
                try {
                    mmSocket.close();
                } catch (Exception e2) {
                    e2.printStackTrace();
                }
                connectionFailed();
                return;
            }
            synchronized (BluetoothService.this) {
                mConnectThread = null;
            }

            connected(mmSocket, mmDevice, mSocketType);
        }

        public void cancel() {
            try {
                if (mmSocket != null) {
                    mmSocket.close();
                }
            } catch (Exception e) {
                Log.e(TAG, "close() of connect " + mSocketType + " socket failed", e);
            }
        }
    }

    private IonHandelDataListener ionHandelData;

    public void setIonHandelDataListener(IonHandelDataListener ionHandelData) {
        this.ionHandelData = ionHandelData;
    }

    public interface IonHandelDataListener {
        void onHandelData(int readByteSize, byte[] buffer, Handler handler);
    }

    /**
     * This thread runs during a connection with a remote device.
     * It handles all incoming and outgoing transmissions.
     */
    private class ConnectedThread extends Thread {
        private final BluetoothSocket mmSocket;
        private final InputStream mmInStream;
        private final OutputStream mmOutStream;
        private boolean sconnected = false;

        public ConnectedThread(BluetoothSocket socket, String socketType) {
            mmSocket = socket;
            InputStream tmpIn = null;
            OutputStream tmpOut = null;
            try {
                tmpIn = socket.getInputStream();
                tmpOut = socket.getOutputStream();
            } catch (Exception e) {
                Log.e(TAG, "temp sockets not created", e);
            }

            mmInStream = tmpIn;
            mmOutStream = tmpOut;
            sconnected = true;
            connectionok();
        }

        public void run() {
            Log.i(TAG, "BEGIN mConnectedThread");
            byte[] buffer = new byte[1024];

            int bytes;
            while (sconnected) {
                try {
                    bytes = mmInStream.read(buffer);
                    if (ionHandelData != null) {
                        ionHandelData.onHandelData(bytes, buffer, mHandler);
                    }
                } catch (Exception e) {
                    Log.e(TAG, "disconnected", e);
                    connectionLost();
                    break;
                }
            }
        }

        /**
         * Write to the connected OutStream.
         * @param buffer  The bytes to write
         */

        public void write(byte[] buffer) {
            try {
                mmOutStream.write(buffer);

            } catch (Exception e) {
                Log.e(TAG, "Exception during write", e);
            }
        }

        public void cancel() {
            try {
                sconnected = false;
                mdevice = null;
                if (mmInStream != null) mmInStream.close();
                if (mmOutStream != null) mmOutStream.close();
                mmSocket.close();
            } catch (Exception e) {
                Log.e(TAG, "close() of connect socket failed", e);
            }
        }
    }

    public DeviceBean getConnectionDevice(Context context) {
        if (mdevice != null) {
            DeviceBean deviceBean = new DeviceBean();
            BluetoothUtil.setDevice(context,mdevice,deviceBean);
            return deviceBean;
        }
        return null;
    }
}
